package com.example.demo.practice.dashboardview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.demo.practice.R;
import com.example.demo.practice.enterprise.Auditinfo;
import com.example.demo.practice.httpserver.HttpServer;
import com.example.demo.practice.ui.TitleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FacilityIfs extends Activity {
    private HttpServer http = new HttpServer();
    private String HTTP = http.getHttp();

    private AutoCompleteTextView search;
    private JSONArray jSONArray;
    private ListView listView;
    private ArrayList<Integer> allId = new ArrayList();
    private ArrayList<String> allEqindex = new ArrayList();
    private List<Auditinfo> mlistInfo = new ArrayList();
    private ArrayList<ArrayList<String>> item = new ArrayList();
    ImageView searchStart;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chargeperson);

        listView = findViewById(R.id.person_info);
        search = findViewById(R.id.search);
        searchStart = findViewById(R.id.searchStart);

        searchStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String SearchName = search.getText().toString().trim();
                setSearchStart(SearchName);
                listView.setAdapter(new ListViewAdapter(mlistInfo));
            }
        });

        getVideoData();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,allEqindex);
        search.setAdapter(adapter);
    }

    public void setSearchStart(String name){
        mlistInfo.clear();
        int i = 0;
        while(i<item.size()){
            if(item.get(i).get(4).equals(name)){
                Auditinfo information = new Auditinfo();
                information.setId(Integer.toString(i));
                information.setText1(item.get(i).get(0));
                information.setText2(item.get(i).get(1));
                information.setText3(item.get(i).get(2) + item.get(i).get(3) + "层");
                information.setText4(item.get(i).get(4));
                mlistInfo.add(information); //将新的info对象加入到信息列表中
            }
            i++;
        }
    }

    public class ListViewAdapter extends BaseAdapter {
        View[] itemViews;

        public ListViewAdapter(List<Auditinfo> mlistInfo) {
            // TODO Auto-generated constructor stub
            itemViews = new View[mlistInfo.size()];
            for(int i=0;i<mlistInfo.size();i++){
                Auditinfo getInfo=mlistInfo.get(i);    //获取第i个对象
                //调用makeItemView，实例化一个Item
                itemViews[i]=makeItemView(
                        getInfo.getText1(), getInfo.getText3(),getInfo.getText4()
                );
            }
        }

        public int getCount() {
            return itemViews.length;
        }

        public View getItem(int position) {
            return itemViews[position];
        }

        public long getItemId(int position) {
            return position;
        }

        //绘制Item的函数
        private View makeItemView(String strText1, String strText3,String strText4) {
            LayoutInflater inflater = (LayoutInflater) FacilityIfs.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联
            View itemView = inflater.inflate(R.layout.facility_item, null);
            TitleView title = findViewById(R.id.title_text_tv);
            title.setText("设备信息");

            // 通过findViewById()方法实例R.layout.item内各组件
            TextView text1 = itemView.findViewById(R.id.text1);
            text1.setText(strText1);    //填入相应的值
            TextView text3 = itemView.findViewById(R.id.text3);
            text3.setText(strText3);
            TextView text4 = itemView.findViewById(R.id.text4);
            text4.setText(strText4);

            return itemView;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                return itemViews[position];
            return convertView;
        }
    }

    public void setInfo(){
        mlistInfo.clear();
        int i=0;
        while(i<item.size()){
            Auditinfo information = new Auditinfo();
            information.setId(Integer.toString(i));
            information.setText1(item.get(i).get(0));
            information.setText3(item.get(i).get(2) + item.get(i).get(3) + "层");
            information.setText4(item.get(i).get(4));

            mlistInfo.add(information); //将新的info对象加入到信息列表中
            i++;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject json = null;
                ArrayList<String> sub = new ArrayList<String>();
                try {
                    json = (JSONObject) jSONArray.get(i);
                    int gid = Integer.valueOf(json.getString("gid"));
                    String name = json.getString("name");
                    String status = json.getString("status");
                    String address = json.getString("address");
                    String floor = json.getString("floor");
                    String eqindex = json.getString("eqindex");

                    sub.add(name);
                    sub.add(status);
                    sub.add(address);
                    sub.add(floor);
                    sub.add(eqindex);
                    item.add(sub);
                    allId.add(gid);
                    allEqindex.add(eqindex);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jSONArray=null;

            setInfo();  //给信息赋值函数，用来测试
            listView.setAdapter(new  ListViewAdapter(mlistInfo));
            //处理Item的点击事件
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Auditinfo getObject = mlistInfo.get(position);   //通过position获取所点击的对象
                    String infoId = getObject.getId(); //获取信息id

                    int ID = allId.get(Integer.valueOf(infoId));
                    Intent intent = new Intent(FacilityIfs.this,FInformations.class);
                    intent.putExtra("ID",ID);
                    startActivity(intent);

                }
            });

            super.handleMessage(msg);
        }
    };

    private void getVideoData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                    Request request = new Request.Builder()
                            .url(HTTP + "getFacilities")//请求接口。如果需要传参拼接到接口后面。
                            .build();//创建Request 对象

                    Response response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        Log.e("kwwl", "response.code()==" + response.code());
                        Log.e("kwwl", "response.message()==" + response.message());
                        //response.body().string()只可以调用一次
                        //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
                        jSONArray = new JSONArray(response.body().string());
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
